package com.zbkj.service.service.foster.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.foster.FosterOrder;
import com.zbkj.common.model.merchant.MerchantAddress;
import com.zbkj.common.model.order.MerchantOrder;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.traceability.Batches;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.traceability.BatchesRequest;
import com.zbkj.service.dao.foster.FosterOrderDao;
import com.zbkj.service.service.BatchesService;
import com.zbkj.service.service.MerchantAddressService;
import com.zbkj.service.service.MerchantOrderService;
import com.zbkj.service.service.OrderDetailService;
import com.zbkj.service.service.foster.FosterOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 代认养订单Service实现类
 * +----------------------------------------------------------------------
 * @author xiaolic
 * +----------------------------------------------------------------------
 */
@Slf4j
@Service
public class FosterOrderServiceImpl extends ServiceImpl<FosterOrderDao, FosterOrder> implements FosterOrderService {

    @Resource
    private FosterOrderDao fosterOrderDao;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private FosterOrderService fosterOrderService;

    @Autowired
    private BatchesService batchesService;
    
    @Autowired
    private MerchantAddressService merchantAddressService;

    /**
     * 分页查询代认养订单
     * @param merchantId 商户ID，传null则查询所有
     * @param userId 用户ID，传null则查询所有
     * @param pageParamRequest 分页参数
     * @return 分页数据
     */
    @Override
    public PageInfo<FosterOrder> getPageList(Integer merchantId, Integer userId, PageParamRequest pageParamRequest) {
        log.info("获取代认养订单分页列表，merchantId={}，userId={}", merchantId, userId);
        
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        
        LambdaQueryWrapper<FosterOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (merchantId != null) {
            lambdaQueryWrapper.eq(FosterOrder::getMerchantId, merchantId);
        }
        if (userId != null) {
            lambdaQueryWrapper.eq(FosterOrder::getUserId, userId);
        }
        lambdaQueryWrapper.orderByDesc(FosterOrder::getCreateTime);
        
        List<FosterOrder> fosterOrderList = fosterOrderDao.selectList(lambdaQueryWrapper);
        
        log.info("获取代认养订单分页列表成功，共查询到{}条数据", fosterOrderList.size());
        return new PageInfo<>(fosterOrderList);
    }

    /**
     * 根据用户ID查询代认养订单列表
     * @param userId 用户ID
     * @return 代认养订单列表
     */
    @Override
    public List<FosterOrder> getListByUserId(Integer userId) {
        log.info("根据用户ID查询代认养订单列表，userId={}", userId);
        
        LambdaQueryWrapper<FosterOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FosterOrder::getUserId, userId);
        lambdaQueryWrapper.orderByDesc(FosterOrder::getCreateTime);
        
        List<FosterOrder> fosterOrderList = fosterOrderDao.selectList(lambdaQueryWrapper);
        
        log.info("根据用户ID查询代认养订单列表成功，共查询到{}条数据", fosterOrderList.size());
        return fosterOrderList;
    }

    /**
     * 根据商户ID查询代认养订单列表
     * @param merchantId 商户ID
     * @return 代认养订单列表
     */
    @Override
    public List<FosterOrder> getListByMerchantId(Integer merchantId) {
        log.info("根据商户ID查询代认养订单列表，merchantId={}", merchantId);
        
        LambdaQueryWrapper<FosterOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FosterOrder::getMerchantId, merchantId);
        lambdaQueryWrapper.orderByDesc(FosterOrder::getCreateTime);
        
        List<FosterOrder> fosterOrderList = fosterOrderDao.selectList(lambdaQueryWrapper);
        
        log.info("根据商户ID查询代认养订单列表成功，共查询到{}条数据", fosterOrderList.size());
        return fosterOrderList;
    }

    /**
     * 根据商品ID查询代认养订单列表
     * @param productId 商品ID
     * @return 代认养订单列表
     */
    @Override
    public List<FosterOrder> getListByProductId(Integer productId) {
        log.info("根据商品ID查询代认养订单列表，productId={}", productId);
        
        LambdaQueryWrapper<FosterOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FosterOrder::getProductId, productId);
        lambdaQueryWrapper.orderByDesc(FosterOrder::getCreateTime);
        
        List<FosterOrder> fosterOrderList = fosterOrderDao.selectList(lambdaQueryWrapper);
        
        log.info("根据商品ID查询代认养订单列表成功，共查询到{}条数据", fosterOrderList.size());
        return fosterOrderList;
    }

    /**
     * 重写getOne方法，添加地址信息查询功能
     * @param queryWrapper 查询条件
     * @return 代认养订单对象（包含地址信息）
     */
    @Override
    public FosterOrder getOne(Wrapper<FosterOrder> queryWrapper) {
//        log.info("调用自定义getOne方法，查询条件: {}", queryWrapper);
        
        // 首先获取订单对象
        FosterOrder fosterOrder = super.getOne(queryWrapper, false);
        
        // 如果订单对象不为空且addressId有效，则查询地址信息
        if (fosterOrder != null && fosterOrder.getAddressId() != null && fosterOrder.getAddressId() > 0) {
//            log.info("订单{}存在有效的addressId: {}, 开始查询地址信息", fosterOrder.getOrderNo(), fosterOrder.getAddressId());
            
            // 通过addressId查询地址信息
            MerchantAddress address = merchantAddressService.getByIdAndIsDelAndIsShow(fosterOrder.getAddressId());
            
            // 如果查询到地址信息，设置到订单对象中
            if (address != null) {
                fosterOrder.setAddress(address);
//                log.info("订单{}的地址信息查询成功并已设置", fosterOrder.getOrderNo());
            } else {
                log.warn("订单{}的地址信息(addressId: {})查询失败", fosterOrder.getOrderNo(), fosterOrder.getAddressId());
            }
        } else {
//            if (fosterOrder == null) {
//                log.info("未查询到订单信息");
//            } else {
//                log.info("订单{}不存在有效的addressId", fosterOrder.getOrderNo());
//            }
        }
        
        return fosterOrder;
    }
    
    /**
     * 根据订单编号创建溯源批次记录
     * @param orderNo 订单编号
     * @return 是否创建成功
     */
    @Override
    public Boolean createTraceBatch(String orderNo) {
        // 1. 查询代认养订单信息
        LambdaQueryWrapper<FosterOrder> fosterOrderQueryWrapper = new LambdaQueryWrapper<>();
        fosterOrderQueryWrapper.eq(FosterOrder::getOrderNo, orderNo);
        FosterOrder fosterOrder = fosterOrderService.getOne(fosterOrderQueryWrapper);

        if (fosterOrder == null) {
            return false;
        }

        log.info("开始创建溯源批次记录，订单编号：{}", orderNo);
        
        // 2. 查询订单详情信息
        LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailQueryWrapper.eq(OrderDetail::getOrderNo, orderNo);
        OrderDetail orderDetail = orderDetailService.getOne(orderDetailQueryWrapper);
        if (orderDetail == null) {
            log.error("未找到订单详情信息，订单编号：{}", orderNo);
            throw new AppException("未找到订单详情信息");
        }
        
        // 3. 查询商户订单信息
        LambdaQueryWrapper<MerchantOrder> merchantOrderQueryWrapper = new LambdaQueryWrapper<>();
        merchantOrderQueryWrapper.eq(MerchantOrder::getOrderNo, orderNo);
        MerchantOrder merchantOrder = merchantOrderService.getOne(merchantOrderQueryWrapper);
        if (merchantOrder == null) {
            log.error("未找到商户订单信息，订单编号：{}", orderNo);
            throw new AppException("未找到商户订单信息");
        }
        
        // 4. 查询该商品最大号段的批次记录
        LambdaQueryWrapper<Batches> batchesQueryWrapper = new LambdaQueryWrapper<>();
        batchesQueryWrapper.eq(Batches::getProductId, orderDetail.getProductId());
        batchesQueryWrapper.eq(Batches::getIsDeleted, 0); // 未删除的批次
        batchesQueryWrapper.orderByDesc(Batches::getEndSerial); // 按结束号段降序
        batchesQueryWrapper.last("LIMIT 1"); // 只取一条记录
        Batches maxBatch = batchesService.getOne(batchesQueryWrapper);
        
        // 5. 计算起始号段
        Long startSerial = 1L;
        if (maxBatch != null && maxBatch.getEndSerial() != null) {
            startSerial = maxBatch.getEndSerial() + 1;
            log.info("找到最大号段批次，productId={}，maxEndSerial={}，新startSerial={}", 
                    orderDetail.getProductId(), maxBatch.getEndSerial(), startSerial);
        } else {
            log.info("未找到商品对应的批次记录，使用默认起始号段：{}", startSerial);
        }
        
        // 6. 计算结束号段
        Long endSerial = startSerial + fosterOrder.getSeedlingCount() - 1;
        
        // 7. 生成批次名称
        String batchName = merchantOrder.getRealName() + "-代认养订单溯源";
        
        // 8. 创建批次请求对象
        BatchesRequest request = new BatchesRequest();
        request.setProductId(orderDetail.getProductId());
        request.setMerchantId(orderDetail.getMerId());
        request.setUserId(orderDetail.getUid());
        request.setOrderNo(orderNo);
        request.setBatchName(batchName);
        request.setStartSerial(startSerial);
        request.setEndSerial(endSerial);
        request.setIsManualSetBatchName(true);
        // 当前时间作为生产日期
        request.setProductionDate(new Date());
        
        // 9. 保存批次信息
        boolean saveResult = batchesService.create(request);
        if (!saveResult) {
            log.error("保存溯源批次记录失败，订单编号：{}", orderNo);
            throw new AppException("保存溯源批次记录失败");
        }

        LambdaQueryWrapper<Batches> batchesQueryWrapper2 = new LambdaQueryWrapper<>();
        batchesQueryWrapper2.eq(Batches::getOrderNo, orderNo);
        Batches batch = batchesService.getOne(batchesQueryWrapper2);

        log.info("溯源批次记录创建成功，批次ID：{}，订单编号：{}", batch.getId(), orderNo);
        
        // 10. 更新代认养订单的溯源批次ID
        fosterOrder.setTraceBatchId(batch.getId());
        fosterOrder.setUpdateTime(new Date());
        boolean updateResult = fosterOrderService.updateById(fosterOrder);
        if (!updateResult) {
            log.error("更新代认养订单溯源批次ID失败，订单编号：{}", orderNo);
            throw new AppException("更新代认养订单溯源批次ID失败");
        }
        log.info("更新代认养订单溯源批次ID成功，订单编号：{}", orderNo);
        
        return true;
    }
}
